//
//  CZStatusViewModel.swift
//  iOSWeibo10
//
//  Created by 李伟鹏 on 16/5/15.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZStatusViewModel: NSObject {
    static let sharedInstance:CZStatusViewModel = CZStatusViewModel()
    
    private var isLoadingStatus = false
    
    private override init(){
        super.init()
    }
    
    func loadStatus(since_id: Int64, max_id: Int64, loadStatusCallback:(statuses: [CZStatus]?,error: NSError?) -> ()){
        
        if isLoadingStatus{
            let error = NSError(domain: "cn.weibo.error.repeatLoadStatus", code: -1, userInfo: ["errorDescription" : "有人正在加载微博数据,直接返回,请下次在来"])
            loadStatusCallback(statuses: nil, error: error)
            return
        }
        isLoadingStatus = true
        guard let access_token = CZUserAccountViewModel.sharedInstance.userAccount?.access_token else{
            CZPrint(items: "access_token没有值,不去请求微博数据")
            return
        }
        // urlString
        let urlString = "2/statuses/home_timeline.json"
        
        var parameters: [String: AnyObject] = ["access_token" : access_token]
        
        if since_id > 0{
                        parameters["since_id"] = NSNumber(longLong: since_id)
        } else if max_id > 0 {
            // 别人传了 max_id,拼接max_id
            parameters["max_id"] = NSNumber(longLong: max_id)
        }
        
        CZNetworkTool.sharedInstance.request(RequestMethod.GET, URLString: urlString, parameters: parameters, success: { (_, responObject) -> Void in
            
            // 网络请求完成了,将正在加载微博的表示改成false
            self.isLoadingStatus = false
            if let result = responObject as? [String:AnyObject]{
                if let statuses = result["statuses"] as? [[String:AnyObject]]{
                    var statusArray = [CZStatus]()
                    for dict in statuses {
                        let statuModel = CZStatus(dict: dict)
                        statusArray.append(statuModel)
                    }
                     loadStatusCallback(statuses:statusArray, error: nil)
                }
               
            }
            }) { (_ , error) -> Void in
                self.isLoadingStatus = false
                 CZPrint(items: "获取微博数据失败了: \(error)")
                 loadStatusCallback(statuses: nil, error: error)
        }
    }
    
    func sendStatus(image:UIImage?, statusString: String, sendStatusCallback: (error: NSError?) -> ()){
        guard let access_token = CZUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            CZPrint(items: "没有access_token")
            return
        }
        
        let prarameters = [
            "access_token" : access_token,
            "status" : statusString
        ]
        if let newImage = image{
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            CZNetworkTool.sharedInstance.POST(urlString, parameters: prarameters, constructingBodyWithBlock: { (formData) -> Void in
                let imageData = UIImagePNGRepresentation(newImage)!
                formData.appendPartWithFileData(imageData, name: "pic", fileName: "123", mimeType: "image/png")
                }, success: { (_, responseObject) -> Void in
                    sendStatusCallback(error: nil)
                }, failure: { (_, error) -> Void in
                    sendStatusCallback(error: error)
            })
        }else {
            // url
            let urlString = "2/statuses/update.json"
            
            // 发送请求 POST
            CZNetworkTool.sharedInstance.request(RequestMethod.POST, URLString: urlString, parameters: prarameters, success: { (_, responseObject) -> Void in
                sendStatusCallback(error: nil)
                }) { (_, error) -> Void in
                    sendStatusCallback(error: error)
            }
        }
        
       
    }
}
